﻿package kizzo.utils 
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.filters.BlurFilter;
	import flash.geom.ColorTransform;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	import flash.display.BlendMode;
	import flash.events.Event;

	public class BloomTweener extends BaseTweener
	{
		private var image:DisplayObject;
		private var bloom:DisplayObject;
		
		private var start_alpha:Number;
		private var start_blur:Number;
		private var end_alpha:Number;
		private var end_blur:Number;	
		private var alpha_step:Number;
		private var blur_step:Number;
		
		public function BloomTweener(image:DisplayObject, steps:uint, end_alpha:Number, end_blur:Number, start_alpha:Number=0, start_blur:Number=0) 
		{			
			this.image = image;	
			this.end_alpha = end_alpha;
			this.end_blur = end_blur;
			this.start_alpha = start_alpha;			
			this.start_blur = start_blur;			
			super(steps);
		}
			
		override protected function init():void
		{					
			var bitmap_data:BitmapData = new BitmapData(this.image.width, this.image.height, true, 0xffffffff);
			var rect:Rectangle = new Rectangle(0, 0, this.image.width, this.image.height);
			bitmap_data.draw(this.image, new Matrix(), new ColorTransform(), BlendMode.NORMAL, rect, true);
			this.bloom = new Bitmap(bitmap_data);
			
			this.alpha_step = (this.end_alpha - this.start_alpha) / this.steps;
			this.blur_step = (this.end_blur - this.start_blur) / this.steps;
			
			if (this.image.parent == null)
				this.image.addEventListener(Event.ADDED, add_bloom);
			else
				add_bloom(null);
		}
			
			
		private function add_bloom(evt:Event):void
		{				
			this.image.removeEventListener(Event.ADDED, add_bloom);			
			this.image.parent.addChild(this.bloom);
			this.bloom.blendMode = BlendMode.OVERLAY;
			this.bloom.x = this.image.x;
			this.bloom.y = this.image.y;			
		}
			
			
		override protected function set_current(step:uint):void
		{			
			this.bloom.alpha = this.start_alpha + step * this.alpha_step;
			
			var blur:Number = this.start_blur + step * this.blur_step;			
				this.bloom.filters = [new BlurFilter(blur, blur, 1 )];			
		}
			
	}
	
}